package com.solotiger.geographic.ui.adapter;

import android.content.Context;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.URLUtil;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeControllerBuilder;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.imagepipeline.image.ImageInfo;
import com.solotiger.geographic.biz.model.Picture;

import java.util.List;

import me.relex.photodraweeview.PhotoDraweeView;

public class PictureAdapter extends PagerAdapter {

    private Context mContext;
    private List<Picture> mPictureList;

    public PictureAdapter(Context context, List<Picture> pictureList) {
        this.mContext = context;
        this.mPictureList = pictureList;
    }

    @Override
    public int getCount() {
        return mPictureList == null ? 0 : mPictureList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        final PhotoDraweeView photoDraweeView = new PhotoDraweeView(mContext);
        PipelineDraweeControllerBuilder controller = Fresco.newDraweeControllerBuilder();
        String path = mPictureList.get(position).getUrl();
        if (URLUtil.isNetworkUrl(path)) {
            controller.setUri(Uri.parse(path));
        } else {
            controller.setUri(Uri.parse("file://" + path));
        }
        controller.setOldController(photoDraweeView.getController());
        controller.setControllerListener(new BaseControllerListener<ImageInfo>() {
            @Override
            public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                super.onFinalImageSet(id, imageInfo, animatable);
                if (imageInfo == null) {
                    return;
                }
                photoDraweeView.update(imageInfo.getWidth(), imageInfo.getHeight());
            }
        });
        photoDraweeView.setController(controller.build());

        try {
            container.addView(photoDraweeView, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return photoDraweeView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(((View) object));
    }

    public Picture getItem(int pos) {
        if (mPictureList == null || getCount() <= pos) {
            return null;
        }
        return mPictureList.get(pos);
    }
}
